/* 
 * Copyright [2018] [Alex/libo(liboware@gmail.com)]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.infodb.user.util;

import com.hyts.infodb.user.bean.po.UserPO;
import lombok.Setter;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;


/** 
 * @author LiBo/Alex
 * @version V1.0 
 */

@Component
public class PasswordHelper {


    @Setter
    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    @Setter
    private String algorithmName = "md5";

    @Setter
    private int hashIterations = 2;

    /**
     *
     * @param user
     */
    public void encryptPassword(UserPO user) {
        user.setSalt(randomNumberGenerator.nextBytes().toHex());
        String newPassword = new SimpleHash(
                //加密算法
                algorithmName,
                //密码
                user.getPassword(),
                //盐值 username+salt
                ByteSource.Util.bytes(user.getSalt()),
                //hash次数
                hashIterations
        ).toHex();
        user.setEncryptPassword(newPassword);
    }

    /**
     *
     * @param password
     * @param salt
     * @return
     */
    public String encryptPasswordStr(String password,String salt) {
        String newPassword = new SimpleHash(
                //加密算法
                algorithmName,
                //密码
                password,
                //盐值 username+salt
                ByteSource.Util.bytes(salt),
                //hash次数
                hashIterations
        ).toHex();
        return newPassword;
    }


    public String main(){
        String newPassword = new SimpleHash(
                //加密算法
                "md5",
                //密码
                "libo",
                //盐值 username+salt
                ByteSource.Util.bytes("infodb"),
                //hash次数
                2
        ).toHex();
        return newPassword;
    }

    public static void main(String[] args){
        System.out.println(new PasswordHelper().main());
    }

}
